//
//  BVLoginViewController.m
//  BuyVegetables
//
//  Created by 叶思超 on 15/10/12.
//  Copyright (c) 2015年 叶思超. All rights reserved.
//

#import "BVLoginViewController.h"
#import "UIView+Extension.h"
#import "BVConst.h"
#import "BVHomeViewController.h"
#import "BVMyInvitedViewController.h"
#import "AppDelegate.h"
#import "HttpTool.h"
#import "MBProgressHUD+MJ.h"

@interface BVLoginViewController ()
/**
 *  手机号phoneF
 */
@property (nonatomic, strong) UITextField *phoneF;
/**
 *  验证码vertifyF
 */
@property (nonatomic, strong) UITextField *vertifyF;
/**
 *  邀请码invitedF
 */
@property (nonatomic, strong) UITextField *invitedF;
/**
 *  第二条分割线
 */

@property (nonatomic,weak) UIView *twoSeparatorLine;
@end

@implementation BVLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 设置导航栏
    [self setupNav];
    
    // 设置UI
    [self setupUI];
}

#pragma mark -- 设置导航栏
- (void)setupNav {
    self.navigationController.navigationBar.barTintColor = BVBaseOrangeColor;
    self.title = @"验证手机";
    self.navigationController.navigationBar.titleTextAttributes = [NSDictionary dictionaryWithObject:[UIColor whiteColor] forKey:NSForegroundColorAttributeName];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back"] style:UIBarButtonItemStyleDone target:self action:@selector(backClick)];
}

#pragma mark -- 设置UI
- (void)setupUI {
    // 手机号
    UIImageView *phoneImage = [[UIImageView alloc] init];
    phoneImage.frame = CGRectMake(20, 84, 15, 25);
    phoneImage.image = [UIImage imageNamed:@"yzsj_phone"];
    [self.view addSubview:phoneImage];
    
    // 输入手机号
    self.phoneF = [[UITextField alloc] init];
    CGFloat phoneX = CGRectGetMaxX(phoneImage.frame) + 10;
    CGFloat phoneY = phoneImage.y;
    CGFloat phoneW = BVScreenW - phoneX - 20;
    CGFloat phoneH = 25;
    self.phoneF.frame = CGRectMake(phoneX, phoneY, phoneW, phoneH);
    self.phoneF.placeholder = @"输入手机号";
    self.phoneF.textColor = BVBaseTextBlackColor;
    [self.phoneF setValue:BVTextLightGrayColor forKeyPath:@"_placeholderLabel.textColor"];
    [self.phoneF setValue:[UIFont boldSystemFontOfSize:15] forKeyPath:@"_placeholderLabel.font"];
    [self.view addSubview:self.phoneF];
    
    // 分割线一
    UIView *oneSeparatorLine = [[UIView alloc] init];
    oneSeparatorLine.frame = CGRectMake(20, CGRectGetMaxY(self.phoneF.frame) + 10, BVScreenW - 20 * 2, 0.7);
    oneSeparatorLine.backgroundColor = BVTextLightGrayColor;
    [self.view addSubview:oneSeparatorLine];
    
    // 发送验证码按钮
    UIButton *sendVertifyButton = [[UIButton alloc] init];
    CGFloat sendY = CGRectGetMaxY(oneSeparatorLine.frame) + 10;
    CGFloat sendW = 70;
    CGFloat sendH = 25;
    CGFloat sendX = BVScreenW - sendW - 20;
    sendVertifyButton.frame = CGRectMake(sendX, sendY, sendW, sendH);
    [sendVertifyButton setTitle:@"发送验证码" forState:UIControlStateNormal];
    [sendVertifyButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    sendVertifyButton.titleLabel.font = [UIFont systemFontOfSize:12];
    sendVertifyButton.backgroundColor = BVBaseOrangeColor;
    sendVertifyButton.layer.masksToBounds = YES;
    sendVertifyButton.layer.cornerRadius = 3;
    [sendVertifyButton addTarget:self action:@selector(sendVertifyButton) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:sendVertifyButton];
    
    // 验证码
    UIImageView *vertifyImage = [[UIImageView alloc] init];
    vertifyImage.frame = CGRectMake(20, CGRectGetMaxY(oneSeparatorLine.frame) + 10, 15, 25);
    vertifyImage.image = [UIImage imageNamed:@"yzsj_code"];
    [self.view addSubview:vertifyImage];
    
    // 输入验证码
    self.vertifyF = [[UITextField alloc] init];
    CGFloat vertifyX = CGRectGetMaxX(vertifyImage.frame) + 10;
    CGFloat vertifyY = vertifyImage.y;
    CGFloat vertifyW = sendX - vertifyX - 10;
    CGFloat vertifyH = 25;
    self.vertifyF.frame = CGRectMake(vertifyX, vertifyY, vertifyW, vertifyH);
    self.vertifyF.placeholder = @"输入验证码";
    self.vertifyF.textColor = BVBaseTextBlackColor;
    [self.vertifyF setValue:BVTextLightGrayColor forKeyPath:@"_placeholderLabel.textColor"];
    [self.vertifyF setValue:[UIFont boldSystemFontOfSize:15] forKeyPath:@"_placeholderLabel.font"];
    [self.view addSubview:self.vertifyF];
    
    // 分割线二
    UIView *twoSeparatorLine = [[UIView alloc] init];
    twoSeparatorLine.frame = CGRectMake(20, CGRectGetMaxY(self.vertifyF.frame) + 10, BVScreenW - 20 * 2, 0.5);
    twoSeparatorLine.backgroundColor = BVTextLightGrayColor;
    [self.view addSubview:twoSeparatorLine];
    self.twoSeparatorLine = twoSeparatorLine;
    
    //邀请码
    UIImageView *invitedImage = [[UIImageView alloc] init];
    invitedImage.frame = CGRectMake(20, CGRectGetMaxY(self.twoSeparatorLine.frame) + 10, 15, 25);
    invitedImage.image = [UIImage imageNamed:@"yzsj_invitation"];
    invitedImage.tag = 300;
    [self.view addSubview:invitedImage];
    
    // 提示语
    UILabel *noticeLabel = [[UILabel alloc] init];
    noticeLabel.frame = CGRectMake(BVScreenW - 20 - 70, CGRectGetMaxY(self.twoSeparatorLine.frame) + 10, 70, 25);
    noticeLabel.font = [UIFont systemFontOfSize:12];
    noticeLabel.text = @"*非必选项";
    noticeLabel.textColor = BVColor(241, 134, 132);
    noticeLabel.tag = 301;
    [self.view addSubview:noticeLabel];
    
    // 获取邀请码
    self.invitedF = [[UITextField alloc] init];
    CGFloat inviteX = CGRectGetMaxX(invitedImage.frame) + 10;
    CGFloat inviteY = invitedImage.y;
    CGFloat inviteW = noticeLabel.x - inviteX - 10;
    CGFloat inviteH = 25;
    self.invitedF.frame = CGRectMake(inviteX, inviteY, inviteW, inviteH);
    self.invitedF.placeholder = @"输入邀请码";
    self.invitedF.textColor = BVBaseTextBlackColor;
    [self.invitedF setValue:BVTextLightGrayColor forKeyPath:@"_placeholderLabel.textColor"];
    [self.invitedF setValue:[UIFont boldSystemFontOfSize:15] forKeyPath:@"_placeholderLabel.font"];
    _invitedF.tag = 302;
    [self.view addSubview:self.invitedF];
    
    // 分割线三
    UIView *threeSeparatorLine = [[UIView alloc] init];
    threeSeparatorLine.frame = CGRectMake(20, CGRectGetMaxY(self.invitedF.frame) + 10, BVScreenW - 20 * 2, 0.5);
    threeSeparatorLine.backgroundColor = BVTextLightGrayColor;
    threeSeparatorLine.tag = 303;
    [self.view addSubview:threeSeparatorLine];

    
    // 开始安钮
    UIButton *startButton = [[UIButton alloc] init];
    startButton.frame = CGRectMake(25, 230.7, BVScreenW - 25 * 2, 40);
    [startButton setTitle:@"开     始" forState:UIControlStateNormal];
    [startButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    startButton.titleLabel.font = [UIFont systemFontOfSize:20];
    startButton.backgroundColor = BVBaseOrangeColor;
    startButton.layer.masksToBounds = YES;
    startButton.layer.cornerRadius = 4;
    startButton.layer.borderWidth = 0.8;
    startButton.layer.borderColor = [UIColor whiteColor].CGColor;
    [startButton addTarget:self action:@selector(startButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:startButton];
    
}
#pragma mark -- 返回
- (void)backClick {
    
    ROOTNAVPOP
}

#pragma mark -- button点击事件
           //============================验证码=========================//
/**
 *  返回首页
 */

- (void)startButtonClick {
    // 拼接路径
    NSString *url = [NSString stringWithFormat:@"%@/VegetableUserAPI/vegetable_user_login", Path];
        
    // 拼接参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    if (self.phoneF.text.length == 0 || [self.phoneF.text isEqualToString:@"输入手机号"]) {
        [MBProgressHUD showError:@"请输入手机号" toView:self.view];
    } else {
        params[@"mobile"] = self.phoneF.text;
        if (self.vertifyF.text.length == 0 || [self.vertifyF.text isEqualToString:@"输入验证码"]){
            [MBProgressHUD showError:@"请输入验证码" toView:self.view];
        } else {
            params[@"verify_code"] = self.vertifyF.text;
            params[@"invite_code"] = self.invitedF.text;
            
            [HttpTool get:url params:params success:^(id responseObj) {
                if ([responseObj[@"code"] isEqualToString:@"1"]) {
                    BVLog(@"登录成功------%@", responseObj);
                    // 存储用户信息
                    NSMutableDictionary * dataDict = [NSMutableDictionary new];
                    
                   dataDict = [NSMutableDictionary dictionaryWithDictionary:(NSDictionary *)responseObj[@"data"]];
                    
                    if (![[dataDict allKeys] containsObject:@"mobile"]) {
                        
                        [dataDict setObject:self.phoneF.text forKey:@"mobile"];
                    
                    }
                    
                    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
                    
                    [defaults setObject:dataDict forKey:@"USERINFO"];
                    [defaults synchronize];
                    
                    NSLog(@"%@",defaults);
                    
                    [[NSNotificationCenter defaultCenter] postNotificationName:LoginSuccessNotification object:nil userInfo:nil];
                    
                   ROOTNAVPOP
                    
                } else {
                    BVLog(@"登录失败------%@", responseObj);
                    
                        [MBProgressHUD showError:@"验证码错误" toView:self.view];
                }
            } failure:^(NSError *error) {
                BVLog(@"请求失败----%@", error);
            }];
        }
    }
}

           //============================获取验证码==========================//
/**
 *  获取验证码
 */
- (void)sendVertifyButton {
    if ([self valiMobile:self.phoneF.text]) {
        // 拼接路径
        NSString *url = [NSString stringWithFormat:@"%@/VegetableUserAPI/getVerifyCodeByUserMobile", Path];
        
        // 拼接参数
        NSMutableDictionary *params = [NSMutableDictionary dictionary];
        params[@"mobile"] = self.phoneF.text;
        NSLog(@"手机号:%@",params[@"mobile"]);
        [HttpTool get:url params:params success:^(id responseObj) {
            if ([responseObj[@"code"] isEqualToString:@"1"]) {
                [MBProgressHUD showSuccess:@"验证码发送成功" toView:self.view];
                [self configInvitedView:responseObj[@"data"][@"status"]];
            } else {
                [MBProgressHUD showError:responseObj[@"msg"]];
            }
        } failure:^(NSError *error) {
            BVLog(@"请求失败----%@", error.description);
        }];
    } else {
        [MBProgressHUD showError:@"手机号非法" toView:self.view];
    }
}
/**
 *  根据是否为老用户  决定是否显示邀请码view
 *
 *  @param status 1   老用户------不显示邀请码view     0   新用户 ---显示邀请码view
 */
- (void)configInvitedView:(NSNumber *)status{
    if (status.integerValue == 1) {
        // 邀请码
    
        for (UIView * subView in self.view.subviews) {
            if (subView.tag >= 300) {
                subView.hidden = YES;
            }
        }
    }
}
#pragma mark - 判断手机号是否合法
- (BOOL)isMobileNumber:(NSString *)mobileNum
{
    /**
     * 手机号码
     * 移动：134[0-8], 135,136,137,138,139,150,151,157,158,159,182,187,188,184
     * 联通：130,131,132,152,155,156,185,186
     * 电信：133,1349,153,180,189
     */
    NSString * MOBILE = @"^1(3[0-9]|5[0-35-9]|8[0-9])\\d{8}$";
    /**
     10         * 中国移动：China Mobile
     11         * 134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     12         */
    NSString * CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[2378])\\d)\\d{7}$";
    /**
     15         * 中国联通：China Unicom
     16         * 130,131,132,152,155,156,185,186
     17         */
    NSString * CU = @"^1(3[0-2]|5[256]|8[56])\\d{8}$";
    /**
     20         * 中国电信：China Telecom
     21         * 133,1349,153,180,189
     22         */
    NSString * CT = @"^1((33|53|8[09])[0-9]|349)\\d{7}$";
    /**
     25         * 大陆地区固话及小灵通
     26         * 区号：010,020,021,022,023,024,025,027,028,029
     27         * 号码：七位或八位
     28         */
    // NSString * PHS = @"^0(10|2[0-5789]|\\d{3})\\d{7,8}$";
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    
    if (([regextestmobile evaluateWithObject:mobileNum] == YES)
        || ([regextestcm evaluateWithObject:mobileNum] == YES)
        || ([regextestct evaluateWithObject:mobileNum] == YES)
        || ([regextestcu evaluateWithObject:mobileNum] == YES))
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

//判断手机号码格式是否正确
- (BOOL)valiMobile:(NSString *)mobile {
    mobile = [mobile stringByReplacingOccurrencesOfString:@" " withString:@""];
    if (mobile.length != 11)
    {
        return NO;
    }else{
        /**
         * 移动号段正则表达式
         */
        NSString *CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";
        /**
         * 联通号段正则表达式
         */
        NSString *CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";
        /**
         * 电信号段正则表达式
         */
        NSString *CT_NUM = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$";
        NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];
        BOOL isMatch1 = [pred1 evaluateWithObject:mobile];
        NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM];
        BOOL isMatch2 = [pred2 evaluateWithObject:mobile];
        NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_NUM];
        BOOL isMatch3 = [pred3 evaluateWithObject:mobile];
        
        if (isMatch1 || isMatch2 || isMatch3) {
            return YES;
        }else{
            return NO;
        }
    }
}

#pragma mark -- 隐藏键盘
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}
@end
